import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
import 'package:gzmall_app/common/color_common.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:gzmall_app/common/fwebView_scaffold.dart';
import 'package:gzmall_app/common/setting_util.dart';
import 'package:gzmall_app/common/toast_util.dart';
import 'package:gzmall_app/hotfix/hotfix.dart';
import 'package:gzmall_app/model/setting.dart';
import 'package:gzmall_app/model/user.dart';
import 'package:gzmall_app/common/net_util.dart';
import 'package:gzmall_app/common/api.dart';
import 'package:path_provider/path_provider.dart';

class SettingPage extends StatefulWidget {
  @override
  SettingPageState createState() {
    return new SettingPageState();
  }
}

class SettingPageState extends State<SettingPage> {
  User _user = User.empty();

  @override
  void initState() {
    super.initState();

    Future.delayed(Duration.zero, () {
      _getUserInfoFromLocate();
    });
  }

  _getUserInfoFromLocate() async {
    await _user.getUserInfo();
    if (_user.id > 0) {
      _getUserInfoFromNet(_user.id);
    }
  }

  _getUserInfoFromNet(int id) {
    NetUtil.get(context, Api.users + id.toString(), (data, message) {
      if (!mounted) return;
      setState(() {
        String _authToken = _user.authToken;
        _user = User.fromJson(data);
        _user.authToken = _authToken;
        User.saveUserInfo(_user);
      });
    }, isInterceptError: false);
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: _createAppBar(),
      body: new Container(
        child: new ListView(
          children: <Widget>[
            GestureDetector(
              onTap: () {
                if (_user.authToken != null && _user.authToken.isNotEmpty) {
                  Navigator.of(context).pushNamed('/person_info_page');
                } else {
                  Navigator.of(context).pushNamed('/login_page').then((v) {
                    _getUserInfoFromLocate();
                  });
                }
              },
              child: _createPersonInfoView(),
            ),
            GestureDetector(
              child: _getSettingItem("我的收货地址", new SizedBox(), 15.0,
                  const EdgeInsets.only(top: 1.0, bottom: 10.0)),
              onTap: () {
                Navigator.of(context).pushNamed('/address_manage');
              },
            ),
            GestureDetector(
              child: _getSettingItem("账户与安全", new SizedBox(), 15.0,
                  const EdgeInsets.only(bottom: 10.0)),
              onTap: () {
                Navigator.of(context).pushNamed('/account_safe');
              },
            ),
            // _getSettingItem("地区设置", new SizedBox(), 15.0,
            //     const EdgeInsets.only(bottom: 1.0)),
            // _getSettingItem("音效与通知", new SizedBox(), 15.0,
            //     const EdgeInsets.only(bottom: 1.0)),
            // _getSettingItem("隐私", new SizedBox(), 15.0,
            //     const EdgeInsets.only(bottom: 10.0)),
            // _getSettingItem("通用", new SizedBox(), 15.0,
            //     const EdgeInsets.only(bottom: 10.0)),
            GestureDetector(
              child: _getSettingItem("问题反馈", new SizedBox(), 15.0,
                  const EdgeInsets.only(bottom: 1.0)),
              onTap: () {
                Navigator.of(context).pushNamed('/feedback_page');
              },
            ),
            Platform.isAndroid
                ? GestureDetector(
                    child: _getSettingItem("用户协议", new SizedBox(), 15.0,
                        const EdgeInsets.only(bottom: 1.0)),
                    onTap: () {
                      String html = Uri.dataFromString(Api.userAgreement,
                          mimeType: 'text/html',
                          parameters: {'charset': 'utf-8'}).toString();
                      Navigator.of(context)
                          .push(new MaterialPageRoute(builder: (_) {
                        return FWebviewScaffold(
                          url: html,
                          userAgent: Api.kWebViewUserAgent,
                          enableMessaging: true,
                          withJavascript: true,
                          clearCache: true,
                          appBar: AppBar(
                            title: Text("用户协议"),
                          ),
                        );
                      }));
                    },
                  )
                : Container(),
            Platform.isAndroid
                ? GestureDetector(
                    child: _getSettingItem("隐私政策", new SizedBox(), 15.0,
                        const EdgeInsets.only(bottom: 1.0)),
                    onTap: () {
                      String html = Uri.dataFromString(Api.privacyPolicy,
                          mimeType: 'text/html',
                          parameters: {'charset': 'utf-8'}).toString();
                      Navigator.of(context)
                          .push(new MaterialPageRoute(builder: (_) {
                        return FWebviewScaffold(
                          url: html,
                          userAgent: Api.kWebViewUserAgent,
                          enableMessaging: true,
                          withJavascript: true,
                          clearCache: true,
                          appBar: AppBar(
                            title: Text("隐私政策"),
                          ),
                        );
                      }));
                    },
                  )
                : Container(),
            // Platform.isAndroid
            //     ? GestureDetector(
            //         child: _getSettingItem("更新补丁", new SizedBox(), 15.0,
            //             const EdgeInsets.only(bottom: 1.0)),
            //         onTap: () {
            //           Hotfix.hotfix();
            //         },
            //       )
            //     : Container(),
            !SettingUtil.isAppStoreAudit()
                ? GestureDetector(
                    child: _getSettingItem(SettingUtil.appName, new SizedBox(),
                        15.0, EdgeInsets.zero),
                    onTap: () {
                      Navigator.of(context).pushNamed('/about');
                    },
                  )
                : Container(),
            _createLogoutView(),
          ],
        ),
      ),
    );
  }

  _createAppBar() {
    return new AppBar(
      elevation: 0.0,
      title: new Text("设置"),
      leading: new IconButton(
        icon: new Icon(Icons.arrow_back_ios),
        onPressed: () {
          Navigator.of(context).pop();
        },
      ),
      actions: <Widget>[],
    );
  }

  _createPersonInfoView() {
    return new Container(
      color: Colors.white,
      padding: const EdgeInsets.only(
          left: 15.0, right: 15.0, top: 10.0, bottom: 10.0),
      child: new Row(
        children: <Widget>[
          new Container(
            width: 48.0,
            height: 48.0,
            margin: const EdgeInsets.only(right: 15.0),
            decoration:
                _user != null && _user.avatar != null && _user.avatar.isNotEmpty
                    ? new BoxDecoration(
                        borderRadius:
                            const BorderRadius.all(Radius.circular(100.0)),
                        image: new DecorationImage(
                          image: new CachedNetworkImageProvider(_user.avatar),
                          fit: BoxFit.fill,
                        ),
                      )
                    : BoxDecoration(
                        color: Colors.grey,
                        borderRadius:
                            const BorderRadius.all(Radius.circular(100.0)),
                      ),
          ),
          new Expanded(
            child: new Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                new Text(
                  _user != null &&
                          _user.nickname != null &&
                          _user.nickname.isNotEmpty
                      ? _user.nickname
                      : "未登录",
                  style: new TextStyle(fontSize: 19.0),
                ),
                new Text(
                  "手机号: " +
                      (_user != null &&
                              _user.phone != null &&
                              _user.phone.isNotEmpty
                          ? _user.phone
                          : ""),
                  style: new TextStyle(fontSize: 10.0),
                ),
              ],
            ),
          ),
          new Image.asset(
            "images/right_arrow.png",
            width: 10.0,
            height: 10.0,
          ),
        ],
      ),
    );
  }

  _createLogoutView() {
    return new GestureDetector(
      onTap: () {
        User.cleanUserToken();
        User.cleanUserInfo();
        Navigator.of(context).pushNamed('/login_page').then((v) {
          _getUserInfoFromLocate();
        });
      },
      child: new Container(
        alignment: Alignment.center,
        height: 50.0,
        margin: const EdgeInsets.only(bottom: 40.0, top: 40.0),
        color: ColorCommon.primaryColor,
        child: new Text(
          "退出当前账户",
          style: new TextStyle(fontSize: 15.0, color: Colors.white),
        ),
      ),
    );
  }

  _getSettingItem(String text, Widget showWidget, double fontSize,
      EdgeInsetsGeometry margin) {
    return new Container(
      margin: margin,
      color: Colors.white,
      padding: const EdgeInsets.all(15.0),
      child: new Row(
        children: <Widget>[
          new Text(
            text,
            style: new TextStyle(fontSize: fontSize),
          ),
          new Expanded(
            child: new Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: <Widget>[
                showWidget,
                new Padding(
                  padding: const EdgeInsets.only(left: 10.0),
                  child: new Image.asset(
                    "images/right_arrow.png",
                    width: 10.0,
                    height: 10.0,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
